<?php

/**
 * 系统设置
 */

namespace app\ph\controller;

class System extends Base
{
    protected $system_model;

    public function __construct()
    {
        parent::__construct();
        $this->system_model = new \app\common\model\System();
    }

    /**
     * 设置首页
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data = $this->system_model->getOne(['id' => 1], '*');
        if (!$data) {
            $this->system_model->addData(['create_time' => time()]);
            $data = $this->system_model->getOne(['id' => 1], '*');
        }
        return view('system/index', ['data' => $data]);
    }

    /**
     * 数据操作
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function data_save()
    {
        $data['title']     = input('post.title');
        $data['brand']     = input('post.brand');
        $data['host']      = input('post.host');
        $data['keywords']  = input('post.keywords');
        $data['represent'] = input('post.represent');
        $data['logo']      = input('post.logo');
        $data['copyright'] = input('post.copyright');
        $data['icp']       = input('post.icp');
        $data['qq']        = input('post.qq');
        $data['we_chat']   = input('post.we_chat');
        $data['tel']       = input('post.tel');
        $id                = input('post.id');

        $validate = new \app\common\validate\System();
        if (!$validate->check($data)) {
            return json(['code' => 100, 'message' => $validate->getError()]);
        }

        if ($id) {
            $data['update_time'] = time();
            $res                 = $this->system_model->editData(['id' => $id], $data);
        } else {
            $res = $this->system_model->addData($data);
        }
        cache("system", $data);
        return operationResult($res, url('System/index'));
    }
}
